<?php

namespace app\api\controller;

use app\common\model\CheckInput;
use app\common\model\CheckLog;
use app\common\model\HiddenDanger;
use fast\Tree;
use think\Db;
use think\Request;

/**
 * @title 检查巡检
 */
class Check extends \app\common\controller\Api
{
    protected $noNeedLogin = ['check_tree', 'from'];
    protected $noNeedRight = '*';

    /**
     * @title 获取检查项信息（分类）
     * @description
     * @return res:结果
     * @author
     * @url /api/check/check_tree
     * @method POST
     */
    public function check_tree(Request $request)
    {
        $check = \app\common\model\Check::all();
        Tree::instance()->init($check);
        $this->success("", Tree::instance()->getTreeArray(0));
    }

    /**
     * @title 获取表单信息
     * @description
     * @param name:check_id type:string require:1  other: default: desc:检查项id
     * @return res:结果
     * @author
     * @url /api/check/from
     * @method POST
     */
    public function from(Request $request)
    {
        $check_id = $request->param("check_id");
        $input_info = CheckInput::where(compact("check_id"))->with("check")->find();
        $this->success("", $input_info);
    }

    /**
     * @title 提交检查结果
     * @description
     * @param name:check_id type:string require:1  other: default: desc:检测项id
     * @param name:duty_user_id type:string require:1  other: default: desc:负责人id
     * @param name:check_target type:string require:1  other: default: desc:检查目的
     * @param name:check_request type:string require:1  other: default: desc:检测要求
     * @param name:check_festival type:string require:1  other: default: desc:检查节日
     * @param name:result_json type:string require:1  other: default: desc:检查结果[{key:{radio: Y=符合/N=不符合, text:问题描述, images:隐患图片,title:"XXXX检测项" }]
     * @return res:结果
     * @author
     * @url /api/check/submit
     * @method POST
     */
    public function submit(Request $request)
    {
        $result_json = $request->param("result_json/a");

        $filter_data = array_filter($result_json, function ($row) {
            if ($row["radio"] === "N") {
                return true;
            } else {
                return false;
            }
        });
        $check_user_id = $this->auth->id;
        $duty_user_id = $request->param("duty_user_id");
        if (!empty($filter_data)) {
            $hidden_danger_data = array_map(function ($row) use ($check_user_id, $duty_user_id) {
                return [
                    'check_user_id' => $check_user_id,
                    'duty_user_id' => $duty_user_id,
                    'hidden_danger_title' => $row["title"],
                    'hidden_danger_images' => $row["images"],
                    'hidden_danger_desc' => $row["text"],
                    'status' => "N"
                ];
            }, $filter_data);
        } else {
            $hidden_danger_data = [];
        }
        $check_log_model = new CheckLog();
        $hidden_danger_model = new HiddenDanger();
        $result = false;
        Db::startTrans();
        try {
            if (!empty($hidden_danger_data)) {
                $hidden_danger_model->saveAll($hidden_danger_data);
            }
            $result = $check_log_model->allowField(true)->save(array_merge($request->param(false), ["check_user_id" => $this->auth->id]));
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error("添加失败");
        }
        $this->success("添加成功");
    }


    /**
     * @title 获取隐患列表
     * @description 分页20条
     * @param name:status type:string require:1  other: default: desc:整改状态Y=已整改，N=待整改
     * @return res:结果
     * @author
     * @url /api/check/get_hidden_danger
     * @method POST
     */
    public function get_hidden_danger(Request $request)
    {
        $status = $request->param("status");
        $danger_data = HiddenDanger::where("status", $status)
            ->with(["checkUser", "dutyUser"])
            ->order("createtime", "desc")->paginate(20);
        $this->success("", $danger_data);
    }

    /**
     * @title 上级检查隐患项提交
     * @description
     * @param name:duty_user_id type:string require:1  other: default: desc:负责人
     * @param name:hidden_danger_title type:string require:1  other: default: desc:隐患标题
     * @param name:hidden_danger_images type:string require:1  other: default: desc:隐患图片
     * @param name:hidden_danger_desc type:string require:1  other: default: desc:隐患详情
     * @return res:结果
     * @author
     * @url /api/check/add_hidden_danger
     * @method POST
     */
    public function add_hidden_danger(Request $request)
    {
        $duty_user_id = $request->param("duty_user_id");
        $hidden_danger_title = $request->param("hidden_danger_title", "");
        $hidden_danger_images = $request->param("hidden_danger_images");
        $hidden_danger_desc = $request->param("hidden_danger_desc");

        $res = HiddenDanger::create([
            'check_user_id' => $this->auth->id,
            'duty_user_id' => $duty_user_id,
            'hidden_danger_title' => $hidden_danger_title,
            'hidden_danger_images' => $hidden_danger_images,
            'hidden_danger_desc' => $hidden_danger_desc,
            'status' => "N"
        ]);
        $this->success("", $res);
    }

    /**
     * @title 获取隐患详情(整改详情)
     * @description
     * @param name:hidden_danger_id type:string require:1  other: default: desc:隐患id
     * @return res:结果
     * @author
     * @url /api/check/hidden_danger_desc
     * @method POST
     */
    public function hidden_danger_desc(Request $request){
        $id = $request->param("hidden_danger_id");
        $res = HiddenDanger::get($id,["checkUser", "dutyUser"]);
        $this->success("", $res);
    }

    /**
     * @title 整改
     * @description
     * @param name:hidden_danger_id type:string require:1  other: default: desc:隐患id
     * @param name:rectify_images type:string require:1  other: default: desc:整改提交图片
     * @param name:rectify_desc type:string require:1  other: default: desc:整改提交情况
     * @return res:结果
     * @author
     * @url /api/check/abarbeitung_hidden_danger
     * @method POST
     */
    public function abarbeitung_hidden_danger(Request $request){
        $hidden_danger_id = $request->param("hidden_danger_id");
        $rectify_images = $request->param("rectify_images");
        $rectify_desc = $request->param("rectify_desc");
        $danger = HiddenDanger::get($hidden_danger_id);
        if (empty($danger)) {
            $this->error("不存在该整改信息");
        }
        if ($danger->duty_user_id != $this->auth->id) {
            $this->error("不是改信息负责人不能提交整改");
        }
        if ($danger->status === "Y") {
            $this->error("改隐患已经整改完成，请勿重复提交整改");
        }
        $danger->rectify_images = $rectify_images;
        $danger->rectify_desc = $rectify_desc;
        $danger->status = "Y";
        $danger->rectify_time = date("Y-m-d H:i:s");
        $danger->save();
        $this->error("整改完成");

    }
}